package com.lance.answer.question_export;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * 05-14 测试保存视频
 */
public class BatchGetGkQuestionAndAnswerByStudent {



    private static List<WebElement> findWeElements(WebDriver driver,String cssSelector,int second){
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    private static WebElement findWeElement(WebDriver driver,String cssSelector,int second){
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                });
    }


    /**
     * 查看作答记录
     */
    private static List<WebElement> findTestingRecords(WebDriver driver){
        // v-btn__content
        List<WebElement> list = Lists.newArrayList();
//        for(WebElement we: (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
//                d -> d.findElements(By.cssSelector("div[class='v-btn__content']")))){
        for(WebElement we: findWeElements(driver,"div[class='v-btn__content'",30)){
            if("查看作答记录".equals(we.getText())){
                list.add(we);
            }
        }
        return list;
    }

    public static void main(String[] args) throws Exception {

        System.err.println("230921199611271219".substring(12));
        System.err.println("23092119961127121X".substring(11,17));
        int sync = 8;
        start(8);

    }

    public static void start(int sync) throws Exception {

        InputStream inputStream2 = new FileInputStream("d:\\allUser.txt");
        List<String> users = IOUtils.readLines(inputStream2, "utf-8");

        List<String> paths = new ArrayList<>();
        List<List<String>> group = new ArrayList<>();
        int size = users.size();
        int step = size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = users.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(users.subList(step * sync, users.size()));
        }
        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                for (String user : batchUser) {
                    String[] strs = user.split(",");
                    String userCode = strs[0];
                    String pwd ;
                    if(strs[1].contains("x")||strs[1].contains("X")){
                        pwd = strs[1].substring(11,17);
                    }else {
                        pwd = strs[1].substring(12);
                    }
                    try {
                        run(userCode,pwd);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }


    }

    public static Set<String> names= Sets.newHashSet();

    public static void run(String username,String pwd) throws Exception{
        WebDriver driver = Util.getDriver("c:\\ynouAutoStudy\\chromedriver.exe");
        String url = "https://xjskk.open.com.cn/stuspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        XinJiangUtil.studentLogin(driver,username,pwd);
        Thread.sleep(5000);
        // 找到我的考试 v-list__tile__title
//        for(WebElement we: (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
//                d -> d.findElements(By.cssSelector("div[class='v-list__tile__title']")))){
        for(WebElement we: findWeElements(driver,"div[class='v-list__tile__title']",20)){
            System.err.println("we.getText():"+we.getText());
            if("我的考试".equals(we.getText())){
                we.click();
                break;
            }
        }
        Thread.sleep(5000);
        List<WebElement> testingRecords = findTestingRecords(driver);
        for(int i=0;i<testingRecords.size();i++){
            Thread.sleep(5000);
            List<WebElement> testingRecords2 = findTestingRecords(driver);
            WebElement  testingRecord = testingRecords2.get(i);
            testingRecord.click();
            Thread.sleep(2000);
            // el-table__row
            WebElement table = findWeElement(driver,"tr[class='el-table__row']",20);
            // 点击查看
            table.findElement(By.tagName("a")).click();
            // TODO 获取信息
            Thread.sleep(5000);
            String name = driver.findElement(By.tagName("h2")).getText();
            if(names.contains(name)){
                continue;
            }
            names.add(name);
            getResult(driver,name);
            // exam-title-i iconfont icon-arrow-left-circle 返回
            driver.findElement(By.cssSelector("i[class='exam-title-i iconfont icon-arrow-left-circle']")).click();
        }

        Thread.sleep(5000);
        driver.close();
        driver.quit();
    }

    public static void getResult(WebDriver driver,String courseName) throws Exception{
        // https://xjskk.open.com.cn/stuspace/#/doExam-history?courseId=27983&homeworkAnswerId=17331695&pageFrom=allCourseExamList
        String currentUrl = driver.getCurrentUrl();
        currentUrl = currentUrl.substring(currentUrl.indexOf("AnswerId=") + 9);
        Thread.sleep(2000);
        String answerId = currentUrl.substring(0, currentUrl.indexOf("&"));
        String getUrl = "https://xjskk.open.com.cn/api/student/student-space-service/examineAnswer/getHistoryDetail?answerId=" + answerId;
        System.err.println("getUrl:" + getUrl);

        Set<Cookie> cookies = driver.manage().getCookies();
        String studentSpaceProfile = XinJiangUtil.getStudentSpaceProfile(cookies);
        String authorization = XinJiangUtil.getAuthorization(cookies);
        System.err.println("studentSpaceProfile:"+studentSpaceProfile);
        System.err.println("authorization:"+authorization);
        String cookie = Util.getCookie(cookies);
        // 初始化头部
        System.out.println("authorization:" + authorization);
        System.out.println("studentSpaceProfile:" + studentSpaceProfile);
        Map<String, String> heads = XinJiangUtil.initStudentHttpHeads(studentSpaceProfile, authorization);

        String result = HttpUtil.get(getUrl, cookie, heads);
        System.out.println("resultresult:"+result);

        String rootPath = "d://xinjiang3//" + courseName + "//";
//        FileUtils.write(new File(rootPath + answerId + ".json"), result, "utf-8");
//        FileUtils.write(new File("d://xinjiang4//" + answerId + ".json"), result, "utf-8");

        FileUtils.write(new File(rootPath + answerId + ".json"), result, "utf-8");
        FileUtils.write(new File("d://xinjiang4//" + courseName + ".json"), result, "utf-8");


    }


}
